import React, { Component, forwardRef, useState, useImperativeHandle, useRef, useEffect } from 'react'
import { View, Text, Image, StyleSheet, TouchableOpacity, Modal, ImageBackground, TouchableWithoutFeedback, Animated, Easing } from 'react-native'
import { connect } from 'react-redux'
import { syncPageGetFriendMsg } from "../redux/features/appSlice"
import { pTx } from "../utils/dimensions"
import { useRealm, useQuery } from '@realm/react'
import { schemaName } from "../realm"
import Realm from "realm"
import httpApi from "../api"
import IconFont from '@pingtou/rn-vant-icons'
import { useNavigation } from '@react-navigation/native';

const SendFriendGrabRedPacket = React.forwardRef((props, ref) => {
    const navigation = useNavigation();
    const realm = useRealm();
    const userInfo = useQuery(schemaName.UserInfo, userInfo => {
        return userInfo.filtered('Current = true');
    })[0];
    const [open, setOpen] = useState(false)
    const [loading, setLoading] = useState(false)
    const params = props.params
    const M = props.item.M?.split(' ')
    const movingValue = useRef(new Animated.Value(0)).current;
    const interpolated = movingValue.interpolate({
        inputRange: [0, 1],
        outputRange: ['0deg', '360deg']
    });
    const anim = useRef(
        Animated.loop(
            Animated.sequence([
                Animated.timing(movingValue, {
                    toValue: 1,
                    duration: 1000,
                    useNativeDriver: true,
                    easing: Easing.linear
                }),
            ])
        )
    )
    const sendFriendGrabRedPacket = async () => {

        try {
            setLoading(true)
            anim.current.start()
            const res = await httpApi.sendFriendGrabRedPacket({
                id: M[0]
            })
            if (res.code == 20) {
                var timestamp = Date.parse(new Date()) / 1000
                realm.write(() => {
                    const filteredRedPacket = realm.objects(schemaName.FriendMsgLis).filtered(`M == '${props.item.M}'`)
                    realm.create(schemaName.FriendMsgLis, { ...filteredRedPacket[0], RedPacketIdState: 1 }, true);
                    const realmItem = {
                        F: props.params.F,
                        M: props.item.M,
                        MT: 14,
                        S: -1,
                        T: timestamp,
                        _id: new Realm.BSON.UUID(),
                        UserId: userInfo.Id,
                        RedPacketId: res.data?.RedPacketId,
                        RedPacketIdState: 1
                    }
                    realm.create(schemaName.FriendMsgLis, realmItem, true);
                    props.syncPageGetFriendMsg(realmItem)
                })
                setTimeout(() => {
                    navigation.navigate('redPacketInfo', {
                        ...userInfo,
                        ...props.item,
                        RedPacketIdState: 1
                    })
                    setOpen(false)
                    anim.current.stop()
                }, 200)

            }
        } catch (error) {

        }
        setLoading(false)
    }

    useImperativeHandle(ref, () => ({
        setOpen,
    }))

    return (
        <Modal
            visible={open}
            animationType="fade"
            transparent={true}
        >
            <View style={styles.centeredView}>
                <ImageBackground source={require('../assets/image/redEnvelope.png')} resizeMode="cover" style={styles.modalView}>
                    <IconFont name="cross" style={[styles.IconFont, styles.rightIconFont]} onPress={() => setOpen(false)} />
                    <View style={styles.sender}>
                        <Image style={styles.senderImage}
                            source={{ uri: httpApi.inline + params.ProfilePhoto }}
                        ></Image>
                        <Text style={styles.senderName} ellipsizeMode={'tail'} numberOfLines={1}>{params.R}</Text>
                    </View>
                    <Text style={styles.senderText}>恭喜发财，大吉大利</Text>
                    <View style={styles.openBox}>
                        <TouchableWithoutFeedback disabled={loading} onPress={() => sendFriendGrabRedPacket()}>
                            <Animated.Text style={[styles.openText, { transform: [{ rotateY: interpolated }] }]}>
                                開
                            </Animated.Text>
                        </TouchableWithoutFeedback>
                    </View>

                </ImageBackground>
            </View >
        </Modal >
    )
})

const FriendGrabRedPacket = React.forwardRef((props, ref) => {
    const packetRefs = useRef(null)
    const item = props.item
    const M = item.M?.split(' ')
    const userInfo = useQuery(schemaName.UserInfo, userInfo => {
        return userInfo.filtered('Current = true');
    })[0];
    const navigation = useNavigation();
    onPickGrabRedPacket = () => {
        if (item.S == -1) {
            navigation.navigate('redPacketInfo', {
                ...userInfo,
                ...item,
            })
        } else {
            if (item.RedPacketIdState == 0) {
                packetRefs.current.setOpen(true)
            } else {
                navigation.navigate('redPacketInfo', {
                    ...props.params,
                    ...item,
                })
            }
        }
    }
    return (
        <>
            <TouchableWithoutFeedback onPress={onPickGrabRedPacket}>
                <View style={[styles.blcok, ["", styles.blcokOpen][[item.RedPacketIdState]]]}>
                    <View style={styles.card}>
                        <Image style={[styles.cardImage]} source={[require('../assets/image/icon30.png'), require('../assets/image/icon31.png')][item.RedPacketIdState]}></Image>
                        <View>
                            <Text style={styles.cardName} >恭喜发财，大吉大利</Text>
                            {item.RedPacketIdState == 1 ? <Text style={styles.cardName} >已领取</Text> : ""}
                        </View>
                    </View>
                    <Text style={styles.styleText}>{['USDT', 'Tweet'][M[1]]}红包</Text>
                </View>
            </TouchableWithoutFeedback>
            <SendFriendGrabRedPacket {...props} ref={packetRefs} />
        </>
    )
})

const mapStateToProps = (state) => ({})

const mapDispatchToProps = {
    syncPageGetFriendMsg
}

export default connect(mapStateToProps, mapDispatchToProps, null, { forwardRef: true })(FriendGrabRedPacket)

const styles = StyleSheet.create({
    blcok: {
        backgroundColor: "#FB9F3C",
        width: pTx(230),
        borderRadius: pTx(6),
    },
    blcokOpen: {
        backgroundColor: "#FFD09E",
    },
    card: {
        flexDirection: "row",
        alignItems: "center",
        marginHorizontal: pTx(15),
        paddingVertical: pTx(10),
        borderBottomColor: "rgba(255,255,255,0.5)",
        borderBottomWidth: 1,
    },
    cardImage: {
        width: pTx(28),
        height: pTx(34),
    },
    cardName: {
        width: pTx(120),
        marginLeft: pTx(15),
        fontSize: pTx(13),
        color: "#fff"
    },
    styleText: {
        paddingHorizontal: pTx(15),
        fontSize: pTx(12),
        paddingVertical: pTx(3),
        color: "#fff"
    },

    centeredView: {
        flex: 1,
        justifyContent: "center",
        alignItems: "center",
        backgroundColor: "rgba(0,0,0,0.2)",
    },
    modalView: {
        position: "relative",
        width: pTx(267),
        height: pTx(441),
        backgroundColor: "white",
        borderRadius: pTx(6),
        shadowColor: "rgba(0,0,0,0.5)",
        shadowOffset: {
            width: 0,
            height: 1
        },
        shadowOpacity: 0.1,
        shadowRadius: 1,
        elevation: 5,
        backgroundColor: "transparent",
    },
    openBox: {
        position: "absolute",
        left: 0,
        right: 0,
        bottom: pTx(49),
        justifyContent: "center",
        alignItems: 'center',
    },
    openText: {
        width: pTx(81),
        height: pTx(81),
        borderRadius: pTx(81),
        backgroundColor: "#ECCC99",
        color: "#040000",
        textAlign: "center",
        textAlignVertical: "center",
        fontSize: pTx(33),
    },
    rightIconFont: {
        position: "absolute",
        right: pTx(15),
        top: pTx(15),
    },
    sender: {
        marginTop: pTx(108),
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "center",
    },
    senderImage: {
        width: pTx(21),
        height: pTx(21),
        borderRadius: pTx(4),
    },
    senderName: {
        marginLeft: pTx(9),
        fontSize: pTx(13),
        color: "#ECCC99"
    },
    senderText: {
        marginTop: pTx(12),
        fontSize: pTx(19),
        color: "#ECCC99",
        textAlign: "center"
    }
})